package com.lxd.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Author Dongdong
 * @注释
 */
@Component
@Slf4j
public class MobileOperatorUtil {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    private final String CODE = "code";
    private final String DATA = "data";
    private final String PROVINCE = "province";
    private final String CITY = "city";
    private final String SP = "sp";
    private final String SPACE = " ";
    private final String SEPARATE = ",";


    //三方查询的地址
    private final String url1 = "https://cx.shouji.360.cn/phonearea.php?number=";

    public String selectAreaAndType(String mobile) {
        String url = url1;
        //向url发送请求获得信息

        String mobileInfoJSON = restTemplate.getForObject(url + mobile, String.class);

        Map map = null;
        //将得到数据转换为map形式
        try {
            map = objectMapper.readValue(mobileInfoJSON, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        Integer code = (Integer) map.get(CODE);
        log.info("code={}",code);
        //如果三方也得不到 返回null
        if (code != 0) {
            return null;
        }
        Map<String, String> areaAndOperator = (Map<String, String>) map.get(DATA);
        String province = areaAndOperator.get(PROVINCE);
        String city = areaAndOperator.get(CITY);
        String sp = areaAndOperator.get(SP);
        log.info("【策略模块-三方调查】province={},city={},sp={}",province,city,sp);
        //3、封装为   省 市,运营商    的格式返回
        return province + SPACE + city + SEPARATE + sp;
    }


}

